package Candidate;


import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;

public class ExportExcel {

	public void exportToExcel(List list, HttpServletResponse response) {	
		
		int i,j;
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("Candidate sheet");
		HSSFCellStyle style = workbook.createCellStyle();
		
		Map<String, Object[]> data = new HashMap<String, Object[]>();
		
		Object[] column = {"Job Code","Reg. No","ID Card Number","Full name","GPA","University","Major Study","Batch Id","Email","Mobile Number"}; 
		
		data.put("1", column);
		for(j=0;j<list.size();j++){
		CandidateModel cm = (CandidateModel)list.get(j);
		data.put(""+(j+2)+"", new Object[] {cm.getJobCd(), cm.getRegisNo(), cm.getIdCardNum(),
				cm.getFullName(), cm.getGpa(), cm.getSchoolName(), cm.getMajority(),cm.getBatchId(),cm.getEmail(), cm.getMobileNumber()});
		}
		Set<String> keyset = data.keySet();
		int rownum = 0;
		Integer strtLineNmber = 1;
		int nKey = keyset.size();
		for (i=strtLineNmber;i<=nKey;i++) {
			String key = Integer.toString(i);
	
		    Row row = sheet.createRow(rownum++);
		    Object [] objArr = data.get(key);
		    int cellnum = 0;
		    for (Object obj : objArr) {
		        Cell cell = row.createCell(cellnum++);
		        if(obj instanceof Date)
		            cell.setCellValue((Date)obj);
		        else if(obj instanceof Boolean)
		            cell.setCellValue((Boolean)obj);
		        else if(obj instanceof String)
		            cell.setCellValue((String)obj);
		        else if(obj instanceof Double)
		            cell.setCellValue((Double)obj);
		    }
		}
		 
		for(i=0;i<column.length;i++){
			sheet.autoSizeColumn(i);
		}
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		try {		
			ServletOutputStream out = response.getOutputStream();
			workbook.write(out);
			out.flush();
			out.close(); 
		     
		} catch (FileNotFoundException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
	}
}
